package websocket

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"mallgo/core"
	"mallgo/internal/common/response"
	"net/http"
)

// WebSocket 升级器
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许所有跨域请求
	},
}

func handleWebSocket(c *gin.Context) {
	clientID := c.Query("id") // 通过 URL 传递客户端唯一 ID
	if clientID == "" {
		c.JSON(http.StatusOK, response.Error(501, "客户端ID不能为空"))
		return
	}

	// 升级 HTTP 连接为 WebSocket
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("WebSocket 连接失败:", err)
		return
	}
	defer pool.RemoveClient(clientID) // 断开时移除客户端

	// 添加连接到池
	pool.AddClient(clientID, conn)

	fmt.Println("客户端连接成功")

	// 处理 WebSocket 消息
	for {
		messageType, msg, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("读取消息失败:", err)
			break
		}

		fmt.Printf("收到消息: %s\n", msg)

		// 发送回客户端
		err = conn.WriteMessage(messageType, msg)
		if err != nil {
			fmt.Println("发送消息失败:", err)
			break
		}
	}
}

func num(ctx *gin.Context) {
	ctx.JSON(200, response.Success(len(pool.clients)))
}

func InitRouter(s *core.AppServer) {
	// 用户路由
	s.Engine.GET("/ws", handleWebSocket)
	s.Engine.GET("/ws_num", num)

}
